package com.example.function;

import com.example.common.support.AjaxResponse;
import com.example.support.OssTemplate;
import com.example.support.OssResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <h1>index</h1>
 * Created by hanqf on 2021/7/13 17:37.
 */

@RestController
@Slf4j
public class IndexController {
    /**
     * 验证码取值范围
     */
    final static String BASE_NUM_LETTER = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";

    @Autowired
    OssTemplate ossTemplate;

    @GetMapping("/")
    public AjaxResponse index(HttpServletRequest request) {
        log.info(request.getSession().getId());
        return AjaxResponse.success("hello world");
    }

    @PostMapping("/file")
    public AjaxResponse file(MultipartFile[] multipartFiles){
        List<OssResult> list = new ArrayList<>();
        if(multipartFiles!=null&&multipartFiles.length>0){
            for(MultipartFile multipartFile:multipartFiles){
                final OssResult ossResult = ossTemplate.uploadFile(multipartFile, multipartFile.getOriginalFilename());
                list.add(ossResult);
            }
        }
        return AjaxResponse.success(list);
    }

    @GetMapping("/vcode")
    public AjaxResponse vcode(HttpServletRequest request) {
        String id = request.getSession().getId();
        System.out.println(id);
        Random random = new Random();
        // 声明返回值
        String vcode = "";
        for (int i = 0; i < 4; i++) {
            // 随机获取 0-61 数字 4次 charAt(num);
            int num = random.nextInt(BASE_NUM_LETTER.length());
            char c1 = BASE_NUM_LETTER.charAt(num);
            vcode += c1;
        }

        Map<String,String> map = new HashMap<>();
        map.put("id", id);
        map.put("vcode", vcode);

        return AjaxResponse.success(map);
    }
}
